import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Config } from '../../entities/config.entity';

@Injectable()
export class ConfigService {
  constructor(
    @InjectRepository(Config)
    private configRepository: Repository<Config>,
  ) {}

  async findAll(): Promise<Config[]> {
    return this.configRepository.find();
  }

  async findOne(key: string): Promise<Config | null> {
    const config = await this.configRepository.findOne({ where: { key } });
    if (config && config.value) {
      try {
        config.value = JSON.parse(config.value);
      } catch (e) {
        // 如果JSON解析失败，保持原值
      }
    }
    return config;
  }

  async createOrUpdate(key: string, value: any, description?: string): Promise<Config> {
    const jsonValue = typeof value === 'string' ? value : JSON.stringify(value);
    
    const existingConfig = await this.configRepository.findOne({ where: { key } });
    
    if (existingConfig) {
      await this.configRepository.update(existingConfig.id, {
        value: jsonValue as any,
        description: description || existingConfig.description,
        updatedAt: new Date(),
      });
      const updatedConfig = await this.findOne(key);
      if (!updatedConfig) {
        throw new Error('更新配置失败');
      }
      return updatedConfig;
    } else {
      const newConfig = this.configRepository.create({
        key,
        value: jsonValue as any,
        description,
      });
      const savedConfig = await this.configRepository.save(newConfig);
      const retrievedConfig = await this.findOne(savedConfig.key);
      if (!retrievedConfig) {
        throw new Error('创建配置失败');
      }
      return retrievedConfig;
    }
  }

  async remove(key: string): Promise<{ success: boolean }> {
    await this.configRepository.delete({ key });
    return { success: true };
  }

}
